import config from '@/config/baidu_translate.json'
import MD5 from '@/utils/md5'
import useMinWaitPromise from './useMinWaitPromise'

interface TranslateQuery {
  q: string
  from: string
  to: string
  appid: string
  salt: string
  [x: string]: string
}

interface Result {
  src: string
  dst: string
}

interface TranslateResponse {
  from: string
  to: string
  trans_result: Result[] // [src, dst]
  src?: string // 原文
  dst?: string // 译文
  error_code?: string
  error_msg?: string
}

/**
 * @description 使用 `百度翻译` 获取菜单文件夹英文
 */
export default async function useTranslate(text: string | string[]): Promise<Result[]> {
  const last = Date.now()

  const query: TranslateQuery = {
    q: [text].flat().join('\n'),
    from: 'zh',
    to: 'en',
    appid: config.appId,
    salt: config.salt
  }

  const SearchParams = new URLSearchParams({
    ...query,
    sign: generateSign({ ...query, secret: config.secret })
  })

  return fetch(`${config.domain}?${SearchParams.toString()}`)
    .then((response) => {
      return response.json()
    })
    .then((translate: TranslateResponse) => {
      const { error_code, error_msg } = translate

      if (error_code && error_code !== config.successCode) {
        throw new Error(`请求翻译出错: ${error_msg}`)
      }

      return translate.trans_result
    })
    .then((result) => {
      return useMinWaitPromise(last, result)
    })
}

const generateSign = (config: TranslateQuery & { secret: string }): string => {
  const { appid, q, salt, secret } = config
  return MD5(`${appid}${q}${salt}${secret}`)
}

/**
 * const reader = response.body?.getReader()

      if (reader) {

        const contentLength = Number(response.headers.get('content-length'))

        let receivedLength = 0
        const chunks: Uint8Array[] = []

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read()

          if (done) break

          chunks.push(value)
          receivedLength += value.length
          console.log('receivedLength', receivedLength)

          if (options?.onprogress) {
            const ratio = receivedLength / contentLength
            const dynamicPercision = ratio.toPrecision(ratio < 10 ? 3 : 4)
            const percent = Number(dynamicPercision)
            options.onprogress(percent)
          }
        }

        const chunksAll = new Uint8Array(receivedLength)
        let offset = 0
        for (const chunk of chunks) {
          chunksAll.set(chunk, offset)
          offset += chunk.length
        }

        const decodedString = String.fromCharCode.apply(null, [...chunksAll])
        const json = JSON.parse(decodedString) as TranslateResponse

        console.log('json', json)

        return json
      }

      return { from: query.from, to: query.to, trans_result: [] }
*/
